package test

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type MyClaims struct {
	UserName string `json:"username"`
	jwt.StandardClaims
}

// 只是学习的实例，所以没有开放
func test() {
	mySigningKey := []byte("chentianyu")
	c := MyClaims{
		UserName: "chen",
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 60,      //当前时间的一分钟之前生效
			ExpiresAt: time.Now().Unix() + 60*60*2, //当前时间的俩小时
			Issuer:    "chen",                      //用户名
		},
	}
	//jwt.NewWithClaims(加密方式,Claims)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	//fmt.Println(token)
	//token.SignedString(key)  //key:官方让我们放一个byte
	s, err := token.SignedString(mySigningKey)
	if err != nil {
		fmt.Printf("%s", err)
	}
	fmt.Println(s) //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNoZW4iLCJleHAiOjE3MDMzMDU0ODMsImlzcyI6ImNoZW4iLCJuYmYiOjE3MDMyOTgyMjN9.saSUB9eK1568jsHT1BWj6M0GHeU6voSCyduNlXNCqlY
	t, e := jwt.ParseWithClaims(s, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if e != nil {
		fmt.Printf("err:%s\n", e)
		return
	}
	//fmt.Println(t) //&{eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNoZW4iLCJleHAiOjE3MDMzMDU0ODMsImlzcyI6ImNoZW4iLCJuYmYiOjE3MDMyOTgyMjN9.saSUB9eK1568jsHT1BWj6M0GHeU6voSCyduNlXNCqlY 0xc000092078 map[alg:HS256 typ:JWT] 0xc0000c8070 saSUB9eK1568jsHT1BWj6M0GHeU6voSCyduNlXNCqlY true}

	fmt.Println(t.Claims.(*MyClaims).UserName) //.(*MyClaims)类型断言
}
